package com.xf.system.utils.excel;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Sheet;

/**
 * @author xiefengf
 * 设置excel初始化格式为文本
 */
public class ExcelExportWriteHandler implements SheetWriteHandler {

    private final Integer columnNum;

    public ExcelExportWriteHandler(Integer columnNum){
        this.columnNum = columnNum;
    }

    @Override
    public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {}

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        for (int i = 0; i < columnNum; i++) {
            // 设置为文本格式
            Sheet sheet = writeSheetHolder.getSheet();
            // 创建单元格样式对象
            CellStyle cellStyle = writeWorkbookHolder.getCachedWorkbook().createCellStyle();
            // 49为文本格式
            cellStyle.setDataFormat((short) 49);
            // i为列，一整列设置为文本格式
            sheet.setDefaultColumnStyle(i, cellStyle);
        }
    }

}
